package com.black.play.common;

import lombok.Getter;
import lombok.Setter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyListener;

/**
 * @author ylx
 */
public abstract class FormComponent<T extends JComponent> extends JPanel {

    protected GridBagConstraints constraints = new GridBagConstraints();
    protected JLabel label;
    protected String value;
    protected T component;
    @Getter
    @Setter
    protected FormDirection direction;

    public FormComponent(String label) {
        this(label, FormDirection.HORIZONTAL);
    }

    public FormComponent(String label, FormDirection direction) {
        this(label, "", direction);
    }

    public FormComponent(String label, String value) {
        this(label, value, FormDirection.HORIZONTAL);
    }

    public FormComponent(String label, String value, FormDirection direction) {
        setLayout(new GridBagLayout());
        this.label = new JLabel(label);
        this.value = value;
        this.direction = direction;
        constraints.insets = new Insets(5, 5, 5, 5);
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1.0;
        constraints.gridx = 0;
        constraints.gridy = 0;
        add(this.label, constraints);
        if (direction == FormDirection.VERTICAL) {
            constraints.gridy++;
        }
        if (direction == FormDirection.HORIZONTAL) {
            constraints.gridx++;
        }
        initComponent();
        add(component, constraints);
    }

    public abstract void initComponent();

    public abstract String getValue();

    public abstract void setText();

    public void setValue(String value) {
        this.value = value;
        setText();
    }

    public String getLabel() {
        return label.getText();
    }

    public Dimension getLabelSize() {
        return label.getPreferredSize();
    }

    public void setLabelSize(Dimension size) {
        label.setPreferredSize(size);
    }

    public Dimension getComponentSize() {
        return component.getPreferredSize();
    }

    public void setComponentSize(Dimension size) {
        component.setPreferredSize(size);
    }

    @Override
    public synchronized void addKeyListener(KeyListener l) {
        super.addKeyListener(l);
        component.addKeyListener(l);
    }
}
